﻿using System;
using System.Web;
using System.Linq;
using DTTB.Common;
using DTTB.MV2.QUANLYNHANSUTIENLUONG.Models.LinQ.LoginHistory;
using Webdiyer.WebControls.Mvc;

namespace DTTB.MV2.QUANLYNHANSUTIENLUONG.BussinessDelegate.LoginHistoryDelegate
{
    public class LoginHistoryDelegate
    {
        DBLoginHistoryDataContext DBLoginHistory = new DBLoginHistoryDataContext();

        //Ghi nhận lại thông tin Login khi sử dụng hệ thống
        public void SaveLoginHistory()
        {
            var lanDangNhap = DBLoginHistory.TB_LoginHistories.Count(p => p.UserId == Convert.ToInt32(HttpContext.Current.Session["USERID"]));

            var loginHistory = new TB_LoginHistory();

            loginHistory.UserId = Convert.ToInt32(HttpContext.Current.Session["USERID"]);
            loginHistory.CreateDate = DateTime.Now;
            loginHistory.LoginDate = DateTime.Now;
            loginHistory.LanDangNhap = lanDangNhap + 1;

            DBLoginHistory.TB_LoginHistories.InsertOnSubmit(loginHistory);
            DBLoginHistory.SubmitChanges();

            //Lấy Id của LoginHistory mới lưu gán cho Session["LoginHistoryId"]
            HttpContext.Current.Session["LoginHistoryId"] = DBLoginHistory.TB_LoginHistories.Where(p => p.UserId == Convert.ToInt32(HttpContext.Current.Session["USERID"])).ToList().Last().Id;
        }

        //Cập nhật lại thông tin đăng nhập , sử dụng khi logout hay hết session
        public void UpdateLoginHistory(int loginHistoryId)
        {
            try
            {
                TB_LoginHistory loginHistory = DBLoginHistory.TB_LoginHistories.SingleOrDefault(p => p.Id == loginHistoryId);
                loginHistory.LogoutDate = DateTime.Now;

                int HourDifference = DateTimeExtension.HourDifference((DateTime)loginHistory.LogoutDate, (DateTime)loginHistory.LoginDate);

                
                loginHistory.UsedSeconds = DateTimeExtension.SecondDifference((DateTime)loginHistory.LogoutDate, (DateTime)loginHistory.LoginDate);
                loginHistory.UsedMinutes = DateTimeExtension.MinuteDifference((DateTime)loginHistory.LogoutDate, (DateTime)loginHistory.LoginDate) + (HourDifference * 60);

                DBLoginHistory.SubmitChanges();
            }
            catch (Exception)
            {
                return;
            }
        }   

        public PagedList<TB_LoginHistory> GetLoginHistoryPagedList(int? id)// id : page id
        {
            return DBLoginHistory.TB_LoginHistories.OrderByDescending(p =>p.Id).ToPagedList(id ?? 1, CommonVariables.PaggedItemsPerPage);
        }
        
        public PagedList<TB_LoginHistory> GetLoginHistoryByUserPagedList(int? id)// id : page id
        {
            return DBLoginHistory.TB_LoginHistories.Where(p => p.UserId == Convert.ToInt32(HttpContext.Current.Session["USERID"])).OrderByDescending(p => p.Id).ToPagedList(id ?? 1, 15);
        }


    }
}